package com.freexiaoyu.cloud.utils

import android.text.TextUtils
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream

object Zip {
    var BUFFERSIZE = 1024

    /**
     * Zip 压缩数据
     *
     * @param unZipStr
     * @return
     */
    fun compressForZip(unZipStr: String): String? {
        if (TextUtils.isEmpty(unZipStr)) {
            return null
        }
        try {
            val baos = ByteArrayOutputStream()
            val zip = ZipOutputStream(baos)
            zip.putNextEntry(ZipEntry("0"))
            zip.write(unZipStr.toByteArray())
            zip.closeEntry()
            zip.close()
            val encode = baos.toByteArray()
            baos.flush()
            baos.close()
            return Base64.encode(encode)
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }

    /**
     * Zip解压数据
     *
     * @param zipStr
     * @return
     */
    fun decompressForZip(zipStr: String?): String? {
        if (TextUtils.isEmpty(zipStr)) {
            return null
        }
        val t = Base64.decode(zipStr)
        try {
            val out = ByteArrayOutputStream()
            val `in` = ByteArrayInputStream(t)
            val zip = ZipInputStream(`in`)
            zip.nextEntry
            val buffer = ByteArray(BUFFERSIZE)
            var n = 0
            while (zip.read(buffer, 0, buffer.size).also { n = it } > 0) {
                out.write(buffer, 0, n)
            }
            zip.close()
            `in`.close()
            out.close()
            return out.toString("UTF-8")
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return null
    }
}